package com.ruiyangwang.ListenBook.service;

import com.ruiyangwang.ListenBook.dataObject.UserDo;
import com.ruiyangwang.ListenBook.repository.UserRepo;
import com.ruiyangwang.ListenBook.viewObject.UserV0;
import lombok.SneakyThrows;
import org.mindrot.jbcrypt.BCrypt;

/**
 * @author syzygy
 * @date 2022/07/09 15:14
 **/
public class UserService {
    private final UserRepo userRepo = new UserRepo();
    public UserV0 register(String username, String password) {
        //对密码进行加盐操作
        String salt = BCrypt.gensalt();
        password = BCrypt.hashpw(password,salt);
        //完成数据库的插入操作
        UserDo userDo = new UserDo(username,password);
        userRepo.insert(userDo);
        //将数据库中直接得到的数据转换成我们的我表现形式
        return new UserV0(userDo);

    }

    @SneakyThrows
    public UserV0 login(String username, String password) {
        //现根据用户名查询密码
        UserDo userDo =userRepo.selectOneByUsername(username);
        if(userDo == null){
            return null;
        }
        //检查密码的正确性
        if(BCrypt.checkpw(password,userDo.password)){
            return new UserV0(userDo);
        }else{
            return null;
        }

    }
}